package xzy.com.controller;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import xzy.com.config.jwt.annotation.PassToken;
import xzy.com.entity.domain.Datum;
import xzy.com.entity.domain.Menu;
import xzy.com.entity.vo.ResponseBean;
import xzy.com.exception.CustomUnauthorizedException;
import xzy.com.service.DatumService;
import xzy.com.service.MenuService;

/**
 * 
 * @author 贾子力
 * 2020年12月19日
 * @Description:资料管理控制层
 */
@RestController
@PassToken
@RequestMapping("/api/datum")
public class DatumController {
	@Autowired
	private DatumService datumService;
	@Autowired
	private MenuService menuService;

	// 文件下载
	@PassToken
	@GetMapping("/fileDownload")
	public void fileDownload(@RequestParam("id") Long id, HttpServletResponse response)
			throws UnsupportedEncodingException {
		if (null == id) {
			throw new CustomUnauthorizedException("id不能为空！");
		}
		Datum datum = datumService.getById(id);
		if (null == datum) {
			throw new CustomUnauthorizedException("文件不存在");
		}
		File file = new File(datum.getUrl());
		if (file.exists()) {
			System.out.println("文件存在" + file.exists());
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;fileName=" + java.net.URLEncoder.encode(datum.getFilename(), "UTF-8"));

			byte[] buffer = new byte[1024];
			// 输出流
			OutputStream os = null;
			try (FileInputStream fis = new FileInputStream(file);
					BufferedInputStream bis = new BufferedInputStream(fis);) {
				os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer);
					i = bis.read(buffer);
				}
				System.out.println("下载成功!");
			} catch (Exception e) {
				e.printStackTrace();
			}
			datum.setNumber(datum.getNumber() + 1);
			datumService.updateById(datum);
		}
	}

	// 文件上传
	@PassToken
	@PostMapping("/fileUpload")
	public ResponseBean add(@RequestParam("file") MultipartFile file) throws FileNotFoundException {
		// 判断文件是否为空，空则返回失败页面
		if (file.isEmpty()) {
			throw new CustomUnauthorizedException("文件为空！");
		}
		// 文件路径
		String path1 = ResourceUtils.getURL("classpath:").getPath();
		String path2 = path1.substring(1, path1.indexOf("target"));
		String path3 = path2 + "src/main/resources/file/";

		// 获取源文件名
		String orginName = file.getOriginalFilename();

		Datum datum = new Datum();
		datum.setFilename(orginName);
		datum.setTitle(orginName.substring(0, orginName.indexOf(".")));
		datum.setUrl(path3 + orginName);
		// 创建文件实例
		File filePath = new File(path3 + orginName);
		// 如果文件目录不存在，创建目录
		if (!filePath.getParentFile().exists()) {
			filePath.getParentFile().mkdirs();
		}

		try {
			file.transferTo(filePath); // 保存文件
			datum.setCreateTime(new Date());
			datumService.save(datum);
			return new ResponseBean(HttpStatus.OK.value(), "文件成功!", null);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}
	//	删除资料
	@PassToken
	@DeleteMapping("/delete/{id}")
	public ResponseBean delete(@PathVariable("id") Long id) {
		if (null != id) {
			Datum datum = datumService.getById(id);
			File file = new File(datum.getUrl());
			if (file.exists()) {
				file.delete();
			}
			boolean isDel = datumService.removeById(id);
			if (isDel) {
				return new ResponseBean(HttpStatus.OK.value(), "删除数据成功!", isDel);
			} else {
				return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除数据失败", null);
			}
		}
		return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "id不能为空", null);
	}

	// 分页处理
	@PassToken
	@GetMapping("/page")
	public ResponseBean listPages(@RequestParam("pages") Integer pages, @RequestParam("size") Integer size) {
		Page<Datum> page = new Page<>(pages, size);
		QueryWrapper<Datum> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("id");
		datumService.page(page, queryWrapper);
		Page<Datum> pages1 = datumService.page(page, queryWrapper);

		Map<String, Object> map = new HashMap<>();
		map.put("list", pages1.getRecords());
		map.put("recordTotal", pages1.getTotal());
		map.put("pageTotal", pages1.getPages());
		return new ResponseBean(HttpStatus.OK.value(), "分页请求成功", map);
	}

	// 搜索查询分页处理
	@PassToken
	@GetMapping("/search")
	public ResponseBean searchListPages(@RequestParam("title") String title, @RequestParam("pages") Integer pages,
			@RequestParam("size") Integer size) {
		Page<Datum> page = new Page<>(pages, size);
		QueryWrapper<Datum> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("id");
		if (null != title) {
			queryWrapper.like("title", title);
		}
		Page<Datum> pages1 = datumService.page(page, queryWrapper);
		// IPage<Menu> menuPage = menuService.findParentMenu(pages1, queryWrapper);
		// 查询父级菜单

		Map<String, Object> map = new HashMap<>();
		map.put("list", pages1.getRecords());
		map.put("recordTotal", pages1.getTotal());
		map.put("pageTotal", pages1.getPages());
		return new ResponseBean(HttpStatus.OK.value(), "分页请求成功", map);
	}

	// 修改
	@PassToken
	@PutMapping("/update")
	public ResponseBean updateUser(@RequestBody Datum datum) {
		if (null != datum) {// 核验数据
			Datum datum2 = datumService.getById(datum.getId());
			String url = datum2.getUrl();
			File file = new File(url);
			String path2 = url.substring(0, url.indexOf(datum2.getFilename()));
			String path3 = path2 + datum.getFilename();
			file.renameTo(new File(path3));
			
			QueryWrapper<Menu>queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("menu_name", datum.getType());
			Menu menu=menuService.getOne(queryWrapper);
			
			datum.setMenuId(menu.getMenuId());
			boolean result = datumService.updateById(datum);
			if (result) {
				new ResponseBean(HttpStatus.OK.value(), "修改成功", true);
			} else {
				return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "修改失败", null);
			}
		}
		return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "修改失败", null);
	}

	@PassToken
	@DeleteMapping("/delete")
	public ResponseBean delete(@RequestParam("id") Integer id) {
		ResponseBean rb = new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null);
		if (null != id) {
			Datum datum = datumService.getById(id);
			File file = new File(datum.getUrl());
			file.delete();
			boolean result = datumService.removeById(id);
			if (result) {
				return new ResponseBean(HttpStatus.OK.value(), "删除成功", true);
			} else {
				return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null);
			}
		}
		return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "id不能为空", null);
	}

	// 传入的json数组key=list，为一组整数索引
	@PassToken
	@DeleteMapping("/deleteAll")
	public ResponseBean deleteAll(@RequestBody JSONObject jsonObject) {
		ResponseBean rb = new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "批量删除失败", null);
		JSONArray jsonArray = jsonObject.getJSONArray("list");
		List<Integer> idList = jsonArray.toJavaList(Integer.class);
		if (!idList.isEmpty()) {
			boolean result = datumService.removeByIds(idList);
			if (result) {
				return new ResponseBean(HttpStatus.OK.value(), "删除成功", true);
			} else {
				return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null);
			}
		}
		return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "id不能为空", null);
	}

}
